//
//  JCMessageTextContentView.swift
//  JChat
//
//  Created by JIGUANG on 2017/3/9.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import MTCategory

open class JCRedPackTipContentView: YYLabel, JCMessageContentViewType {

    
    private weak var _delegate: JCMessageDelegate?
    private var _message: JCMessageType!
    public override init(frame: CGRect) {
        super.init(frame: frame)
        _commonInit()
    }
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        _commonInit()
    }

    open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return super.canPerformAction(action, withSender: sender)
    }
    
    open func apply(_ message: JCMessageType) {
        guard let content = message.content as? JCRedPackTipContent else {
            return
        }
        
//        self.attributedText = content.text
//        self.textColor = UIColor.white
//        self.font = PingFangSCRegularFont(14)
//        self.textAlignment = .center
        _delegate = content.delegate
        _message = message
        self.isUserInteractionEnabled = true
        
        // "[\"messageType\": pullnotify, \"pullUserName\": mitu_IqkMmGYt, \"pullNickname\": 打SEI勒, \"id\": 209, \"senderNickname\": almost, \"senderUserName\": mitu_5SEfpnBB]"
        //if let infos = content.infos {
        let attribute: NSMutableAttributedString = NSMutableAttributedString(attributedString: content.text)
        
        if let highlightRange = attribute.string.nsrange(of: "红包").last {
            attribute.setTextHighlight(highlightRange, color: UIColor.red, backgroundColor: nil, userInfo: nil, tapAction: { [weak self] (v, attributeString, range, rect) in
                guard let weakSelf = self else { return }
                weakSelf._clickCell()
            }, longPressAction: nil)
        }
        
        self.attributedText = attribute
//        }
    }
    
    private func _commonInit() {
//        layer.cornerRadius = 2.5
//        layer.borderWidth = 1.0
//        layer.borderColor = UIColor(hex: 0xD7DCE2).cgColor
//        layer.masksToBounds = true
        font = PingFangSCMediumFont(10)
//        backgroundColor = UIColor(hex: 0xffffff, alpha: 0.7)
        //backgroundColor = UIColor(hex: 0x999999)
//        textColor = .white
//        textAlignment = .center
        _tapGesture()
        numberOfLines = 0
    }
    
    func _tapGesture() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(_clickCell))
        tap.numberOfTapsRequired = 1
        addGestureRecognizer(tap)
    }
    
    @objc func _clickCell() {
        _delegate?.tapRedPackNotify?(message: _message)
    }
}


